<template>
  <div class="defect-trace-result">
    <!-- 缺陷基本信息 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="defect-card">
          <div slot="header" class="card-header">
            <span>缺陷基本信息</span>
            <el-button type="primary" size="small" @click="exportData">
              <i class="el-icon-download"></i> 导出记录
            </el-button>
          </div>
          <el-descriptions :column="4" border>
            <el-descriptions-item label="缺陷编号">{{ traceData.defect?.defectCode || '--' }}</el-descriptions-item>
            <el-descriptions-item label="缺陷类型">{{ traceData.defect?.defectName || '--' }}</el-descriptions-item>
            <el-descriptions-item label="产品名称">{{ traceData.defect?.productName || '--' }}</el-descriptions-item>
            <el-descriptions-item label="批次编号">{{ traceData.defect?.batchNo || '--' }}</el-descriptions-item>
            <el-descriptions-item label="发现工序">{{ traceData.defect?.processName || '--' }}</el-descriptions-item>
            <el-descriptions-item label="发现时间">{{ traceData.defect?.findTime || '--' }}</el-descriptions-item>
            <el-descriptions-item label="报告人">{{ traceData.defect?.reporter || '--' }}</el-descriptions-item>
            <el-descriptions-item label="缺陷状态">
              <el-tag :type="getDefectStatusType(traceData.defect?.status)">
                {{ getDefectStatusText(traceData.defect?.status) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
          
          <el-divider content-position="left">缺陷描述</el-divider>
          <div class="defect-description">
            <p>{{ traceData.defect?.description || '暂无描述' }}</p>
          </div>
          
          <el-divider content-position="left">缺陷图片</el-divider>
          <div class="defect-images" v-if="traceData.defect?.images && traceData.defect.images.length > 0">
            <el-image 
              v-for="(image, index) in traceData.defect.images" 
              :key="index"
              :src="image.url" 
              :preview-src-list="getImageUrls()"
              fit="cover"
              class="defect-image">
            </el-image>
          </div>
          <div v-else class="empty-data">
            <el-empty description="暂无图片"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 缺陷传播路径 -->
    <el-row :gutter="20" class="path-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>缺陷传播路径</span>
          </div>
          <div class="graph-container" ref="propagationGraph"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 根本原因分析 -->
    <el-row :gutter="20" class="rca-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>根本原因分析</span>
          </div>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12">
              <div class="fishbone-container" ref="fishboneChart"></div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12">
              <div class="causes-list">
                <el-collapse v-model="activeCauses">
                  <el-collapse-item 
                    v-for="(category, index) in traceData.rca?.causes" 
                    :key="index"
                    :title="category.category"
                    :name="index">
                    <el-table :data="category.items" border style="width: 100%">
                      <el-table-column prop="cause" label="原因"></el-table-column>
                      <el-table-column prop="probability" label="可能性">
                        <template v-slot="scope">
                          <el-rate 
                            v-if="scope && scope.row"
                            v-model="scope.row.probability" 
                            disabled 
                            text-color="#ff9900">
                          </el-rate>
                          <span v-else>--</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="verified" label="验证状态">
                        <template v-slot="scope">
                          <el-tag v-if="scope && scope.row" :type="scope.row.verified ? 'success' : 'info'">
                            {{ scope.row.verified ? '已验证' : '未验证' }}
                          </el-tag>
                          <span v-else>--</span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-collapse-item>
                </el-collapse>
                
                <div v-if="traceData.rca?.rootCause" class="root-cause-section">
                  <el-divider content-position="left">根本原因</el-divider>
                  <el-alert
                    :title="traceData.rca.rootCause.title"
                    :description="traceData.rca.rootCause.description"
                    type="error"
                    show-icon
                    :closable="false">
                  </el-alert>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 纠正措施 -->
    <el-row :gutter="20" class="actions-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>纠正措施</span>
          </div>
          <el-steps direction="vertical" :active="getActiveStepIndex()">
            <el-step 
              v-for="(action, index) in traceData.correctiveActions" 
              :key="index"
              :title="action.title"
              :description="action.description">
              <template slot="icon">
                <el-tag 
                  :type="getActionStatusType(action.status)"
                  size="medium"
                  effect="dark"
                  class="step-status-tag">
                  {{ getActionStatusText(action.status) }}
                </el-tag>
              </template>
            </el-step>
          </el-steps>
          
          <div v-if="!traceData.correctiveActions || traceData.correctiveActions.length === 0" class="empty-data">
            <el-empty description="尚未制定纠正措施"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预防措施 -->
    <el-row :gutter="20" class="preventive-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>预防措施</span>
          </div>
          <el-table :data="traceData.preventiveActions || []" style="width: 100%">
            <el-table-column prop="type" label="类型"></el-table-column>
            <el-table-column prop="action" label="措施内容"></el-table-column>
            <el-table-column prop="department" label="负责部门"></el-table-column>
            <el-table-column prop="owner" label="负责人"></el-table-column>
            <el-table-column prop="deadline" label="截止日期"></el-table-column>
            <el-table-column prop="status" label="状态">
              <template v-slot="scope">
                <el-tag v-if="scope && scope.row" :type="getActionStatusType(scope.row.status)">
                  {{ getActionStatusText(scope.row.status) }}
                </el-tag>
                <span v-else>--</span>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="!traceData.preventiveActions || traceData.preventiveActions.length === 0" class="empty-data">
            <el-empty description="尚未制定预防措施"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 相似缺陷 -->
    <el-row :gutter="20" class="similar-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>相似缺陷</span>
          </div>
          <el-table :data="traceData.similarDefects || []" style="width: 100%">
            <el-table-column prop="defectCode" label="缺陷编号"></el-table-column>
            <el-table-column prop="defectName" label="缺陷类型"></el-table-column>
            <el-table-column prop="productName" label="产品"></el-table-column>
            <el-table-column prop="batchNo" label="批次"></el-table-column>
            <el-table-column prop="findTime" label="发现时间"></el-table-column>
            <el-table-column prop="similarity" label="相似度">
              <template v-slot="scope">
                <el-progress 
                  v-if="scope && scope.row"
                  :percentage="(scope.row.similarity || 0) * 100" 
                  :color="getSimilarityColor(scope.row.similarity || 0)">
                </el-progress>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template v-slot="scope">
                <el-button
                  v-if="scope && scope.row"
                  @click.native.prevent="viewDefectDetails(scope.row)"
                  link
                  size="small">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="!traceData.similarDefects || traceData.similarDefects.length === 0" class="empty-data">
            <el-empty description="暂无相似缺陷"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { exportDefectTrace } from "@/api/qep/dataAnalysis";

export default {
  name: "DefectTraceResult",
  props: {
    traceData: {
      type: Object,
      required: true
    },
    defectName: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      propagationGraph: null,
      fishboneChart: null,
      activeCauses: [0] // 默认展开第一个原因类别
    }
  },
  mounted() {
    this.$nextTick(() => {
      try {
        if (this.traceData && this.traceData.propagation && 
            this.traceData.propagation.nodes && this.traceData.propagation.nodes.length > 0) {
          this.initPropagationGraph();
        }
        if (this.traceData && this.traceData.rca && 
            this.traceData.rca.causes && this.traceData.rca.causes.length > 0) {
          this.initFishboneChart();
        }
        window.addEventListener('resize', this.resizeCharts);
      } catch (error) {
        console.error('Error initializing charts:', error);
      }
    });
  },
  beforeDestroy() {
    try {
      if (this.propagationGraph) {
        this.propagationGraph.dispose();
        this.propagationGraph = null;
      }
      if (this.fishboneChart) {
        this.fishboneChart.dispose();
        this.fishboneChart = null;
      }
      window.removeEventListener('resize', this.resizeCharts);
    } catch (error) {
      console.error('Error disposing charts:', error);
    }
  },
  methods: {
    // 获取图片URL列表
    getImageUrls() {
      if (!this.traceData?.defect?.images) return [];
      return this.traceData.defect.images.map(image => image.url || '');
    },
    
    // 初始化缺陷传播路径图
    initPropagationGraph() {
      if (!this.$refs.propagationGraph) return;
      if (!this.traceData?.propagation?.nodes || !this.traceData?.propagation?.links) return;
      
      try {
        if (this.propagationGraph) {
          this.propagationGraph.dispose();
        }
        
        this.propagationGraph = echarts.init(this.$refs.propagationGraph);
        
        const option = {
          tooltip: {
            trigger: 'item',
            triggerOn: 'mousemove'
          },
          series: [
            {
              type: 'sankey',
              layout: 'none',
              emphasis: {
                focus: 'adjacency'
              },
              data: this.traceData.propagation.nodes.map(node => ({
                name: node.name || '未知节点',
                value: node.value || 1,
                itemStyle: {
                  color: node.color || undefined
                }
              })),
              links: this.traceData.propagation.links.map(link => ({
                source: link.source || '',
                target: link.target || '',
                value: link.value || 1
              })),
              lineStyle: {
                color: 'gradient',
                curveness: 0.5
              }
            }
          ]
        };
        
        this.propagationGraph.setOption(option);
      } catch (error) {
        console.error('Failed to initialize propagation graph:', error);
      }
    },
    
    // 初始化鱼骨图
    initFishboneChart() {
      if (!this.$refs.fishboneChart) return;
      if (!this.traceData.rca || !this.traceData.rca.causes || !Array.isArray(this.traceData.rca.causes)) return;
      
      try {
        if (this.fishboneChart) {
          this.fishboneChart.dispose();
        }
        
        this.fishboneChart = echarts.init(this.$refs.fishboneChart);
        
        // 准备鱼骨图数据
        const categories = this.traceData.rca.causes.map(item => item.category || '未知类别');
        const data = [];
        
        // 根节点
        data.push({
          name: '缺陷',
          value: 10,
          itemStyle: {
            color: '#F56C6C'
          }
        });
        
        // 添加大类
        categories.forEach((category, index) => {
          data.push({
            name: category,
            value: 8,
            itemStyle: {
              color: this.getCategoryColor(index)
            }
          });
        });
        
        // 添加子项
        let childIndex = categories.length + 1;
        const links = [];
        
        // 连接根节点和大类
        categories.forEach((category, index) => {
          links.push({
            source: '缺陷',
            target: category,
            lineStyle: {
              color: this.getCategoryColor(index)
            }
          });
          
          // 添加子项并连接
          const items = this.traceData.rca.causes[index].items || [];
          items.forEach(item => {
            const nodeName = item.cause || '未知原因';
            data.push({
              name: nodeName,
              value: (item.probability || 0.5) * 2,
              itemStyle: {
                color: item.verified ? '#67C23A' : '#E6A23C'
              }
            });
            
            links.push({
              source: category,
              target: nodeName,
              lineStyle: {
                color: this.getCategoryColor(index),
                opacity: 0.7
              }
            });
            
            childIndex++;
          });
        });
        
        const option = {
          tooltip: {
            trigger: 'item',
            triggerOn: 'mousemove'
          },
          series: [
            {
              type: 'graph',
              layout: 'force',
              animation: true,
              roam: true,
              label: {
                show: true,
                position: 'right',
                formatter: '{b}'
              },
              draggable: true,
              data: data,
              force: {
                repulsion: 100,
                gravity: 0.1,
                edgeLength: [50, 100]
              },
              edges: links
            }
          ]
        };
        
        this.fishboneChart.setOption(option);
      } catch (error) {
        console.error('Failed to initialize fishbone chart:', error);
      }
    },
    
    // 获取根因分类颜色
    getCategoryColor(index) {
      const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#9B59B6'];
      return colors[index % colors.length];
    },
    
    // 图表大小调整
    resizeCharts() {
      try {
        if (this.propagationGraph && this.$refs.propagationGraph) {
          this.propagationGraph.resize();
        }
        if (this.fishboneChart && this.$refs.fishboneChart) {
          this.fishboneChart.resize();
        }
      } catch (error) {
        console.error('Error resizing charts:', error);
      }
    },
    
    // 获取相似度颜色
    getSimilarityColor(similarity) {
      if (similarity >= 0.8) return '#F56C6C';
      if (similarity >= 0.6) return '#E6A23C';
      return '#67C23A';
    },
    
    // 获取活动步骤索引
    getActiveStepIndex() {
      if (!this.traceData.correctiveActions) return 0;
      
      // 找出最后一个已完成的操作的索引
      for (let i = this.traceData.correctiveActions.length - 1; i >= 0; i--) {
        if (this.traceData.correctiveActions[i].status === 'completed') {
          return i + 1;
        }
      }
      
      return 0;
    },
    
    // 缺陷状态
    getDefectStatusType(status) {
      const statusMap = {
        'open': 'danger',
        'in_progress': 'warning',
        'resolved': 'success',
        'closed': 'info'
      };
      return statusMap[status] || 'info';
    },
    getDefectStatusText(status) {
      const statusMap = {
        'open': '未处理',
        'in_progress': '处理中',
        'resolved': '已解决',
        'closed': '已关闭'
      };
      return statusMap[status] || '未知';
    },
    
    // 纠正措施状态
    getActionStatusType(status) {
      const statusMap = {
        'planned': 'info',
        'in_progress': 'warning',
        'completed': 'success',
        'overdue': 'danger',
        'canceled': 'info'
      };
      return statusMap[status] || 'info';
    },
    getActionStatusText(status) {
      const statusMap = {
        'planned': '计划中',
        'in_progress': '进行中',
        'completed': '已完成',
        'overdue': '已逾期',
        'canceled': '已取消'
      };
      return statusMap[status] || '未知';
    },
    
    // 查看相似缺陷
    viewSimilarDefect(defect) {
      // 跳转到该缺陷的追溯页面
      this.$router.push({
        path: '/qep/data-analysis/trace',
        query: {
          type: 'defect',
          defectId: defect.defectCode
        }
      });
    },
    
    // 导出数据
    exportData() {
      // 尝试从多个位置获取缺陷名称
      let defectName = this.traceData?.defect?.defectName;
      
      // 如果缺陷名称不存在，尝试从props获取
      if (!defectName && this.defectName) {
        defectName = this.defectName;
      }
      
      if (!defectName) {
        this.$message.warning('无法获取缺陷名称，导出失败');
        return;
      }
      
      this.$message({
        message: '正在导出数据，请稍候...',
        type: 'info'
      });
      
      exportDefectTrace(defectName).then(() => {
        this.$message.success('导出成功');
      }).catch(err => {
        console.error('导出失败:', err);
        this.$message.error('导出功能暂未实现，请联系管理员添加导出接口');
      });
    }
  }
}
</script>

<style scoped>
.defect-trace-result {
  margin-top: 20px;
}
.defect-card {
  margin-bottom: 20px;
}
.defect-description {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  min-height: 40px;
}
.defect-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.defect-image {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
}
.path-row, .rca-row, .actions-row, .preventive-row, .similar-row {
  margin-top: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.graph-container {
  height: 400px;
  width: 100%;
}
.fishbone-container {
  height: 400px;
  width: 100%;
}
.causes-list {
  height: 400px;
  overflow-y: auto;
}
.root-cause-section {
  margin-top: 20px;
}
.step-status-tag {
  padding: 2px 5px;
  margin-right: 5px;
}
.empty-data {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}
</style> 